﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;

using AddProductLib.UserTextBox;
using SkladLib;
using MessageBox = System.Windows.MessageBox;

namespace AddProductLib
{
    public partial class WPridatZbozi : Window
    {

        #region Proměnné + Metody

        private int _cenaZbozi;

        private Zbozi _zbozi;

        private DateTime _odDne = DateTime.Now;

        private bool _canClose;

        // spocitat rozdil mezi 2 datumy
        private static int PocetDnu(DateTime od, DateTime doKdy)
        {
            TimeSpan rozdil = doKdy.Date.Subtract(od.Date);
            return rozdil.Days;
        }

        private void VynulovatHodnoty()
        {
            tb_CarovyKod.Text = "";
            tb_Nazev.Text = "";
            tb_PocetDni.Text = "1";
            sb_Rezerva.Value = 0;
            tb_CelkovaCena.Text = "0";

            lb_StatusZbozi.Visibility = Visibility.Hidden;
            lb_Stav.Visibility = Visibility.Hidden;

            _zbozi = null;
        }

        private void PrepocitatCenu()
        {
            try
            {
                if (_zbozi == null) return;
                int pocetDni = int.Parse(tb_PocetDni.Text);
                int cena;
                switch (pocetDni)
                {
                    case 1:
                        cena = _zbozi.cenovyProfil.days[0];
                        break;
                    case 2:
                        cena = _zbozi.cenovyProfil.days[1];
                        break;
                    case 3:
                        cena = _zbozi.cenovyProfil.days[2];
                        break;
                    case 4:
                        cena = _zbozi.cenovyProfil.days[3];
                        break;
                    case 5:
                        cena = _zbozi.cenovyProfil.days[4];
                        break;
                    case 6:
                        cena = _zbozi.cenovyProfil.days[5];
                        break;
                    case 7:
                        cena = _zbozi.cenovyProfil.days[6];
                        break;
                    default:
                        cena = _zbozi.cenovyProfil.days[6] + (pocetDni - 7) * _zbozi.cenovyProfil.dayDif;
                        break;
                }

                _cenaZbozi = cena;
                tb_CelkovaCena.Text = _cenaZbozi.ToString();
            }
            catch (Exception)
            {
                MessageBox.Show("Neplatné parametry zboží !", "Upozornění", MessageBoxButton.YesNo,
                                MessageBoxImage.Warning);
            }
        }

        private void UpdateStatus()
        {

            if (_zbozi == null)
            {
                lb_StatusZbozi.Visibility = Visibility.Hidden;
                lb_Stav.Visibility = Visibility.Hidden;
                MujExpander.Visibility = Visibility.Hidden;
            }

            else
            {
                List<Rezervace> listRezervace = _zbozi.rezervace;

                lb_StatusZbozi.Visibility = Visibility.Visible;
                lb_Stav.Visibility = Visibility.Visible;

                if (listRezervace.Count == 0)
                {
                    lb_StatusZbozi.Content = "Dostupný";
                    lb_StatusZbozi.Foreground = Brushes.DarkGreen;

                    _odDne = DateTime.Now;
                    date_OdDne.SelectedDate = _odDne;

                    MujExpander.Visibility = Visibility.Hidden;
                }
                else
                {
                    MujExpander.Visibility = Visibility.Visible;

                    list_Prehled.Items.Clear();

                    foreach (Rezervace rezervace in listRezervace)
                    {
                        list_Prehled.Items.Add(new RezervaceZakaznik("Jméno: " + rezervace.Name,
                                "Od:    " + rezervace.DateFrom.ToShortDateString(),
                                "Do:    " + rezervace.DateIn.ToShortDateString()));
                        _odDne = rezervace.DateIn.AddDays(1);
                    }

                    lb_StatusZbozi.Content = "Rezervovaný";
                    lb_StatusZbozi.Foreground = Brushes.Red;

                    //Edit Rosko Prosim opravit program vyse !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                    //spatne se nastavoval datum od nerozumim proč podle rezervace
                    //_odDne = DateTime.Now;
                    //date_OdDne.SelectedDate = _odDne;
                    //**************************************************************************
                    //Martin - protože muze se stat ze uzivatel nastavi datum, kdy je zbozi rezervovano !!!!
                }

            }

        }

        #endregion

        #region Form

        // konstruktor bez parametru
        public WPridatZbozi()
        {
            InitializeComponent();

            tb_CarovyKod.Focus();
        }

        // konstruktor bez parametru
        public WPridatZbozi(string carovyKod)
        {
            InitializeComponent();

            _zbozi = Zbozi.GetZboziByCode(carovyKod);

            try
            {

                tb_CarovyKod.Text = carovyKod;
                tb_Nazev.Text = _zbozi.name;
                tb_CarovyKod.Focus();
            }
            catch (Exception)
            {
                MessageBox.Show("Produkt není zaznamenán v databázi", "Upozornění", MessageBoxButton.OK, MessageBoxImage.Warning);
                this.Close();
            }

        }

        // konstruktor s parametry - pro možnost Upravit
        public WPridatZbozi(NovyZbozi novy)
        {
            InitializeComponent();
            
            if (novy.CarovyKod != string.Empty)
            {
                _zbozi = Zbozi.GetZboziByCode(novy.CarovyKod);

                tb_CarovyKod.Text = novy.CarovyKod;
                lb_CenovyProfil.Content = _zbozi.cenovyProfil.name;
            }

            else
            {
                _zbozi = null;
                tb_CarovyKod.Text = "neznámý";
                lb_CenovyProfil.Content = "neznámý";
            }
            
            tb_Nazev.Text = novy.Nazev;

            this._cenaZbozi = int.Parse(novy.Cena);

            tb_CelkovaCena.Text = _cenaZbozi.ToString();
            date_OdDne.SelectedDate = novy.OdDne;
            _odDne = novy.OdDne; ;
            tb_PocetDni.Text = novy.PocetDni;
            sb_Rezerva.Value = novy.Rezerva;

            tb_CarovyKod.Focus();
        }

        private void Okno_Loaded(object sender, RoutedEventArgs e)
        {
            date_OdDne.SelectedDateChanged += date_OdDne_SelectedDateChanged;

            if (tb_PocetDni.Text == string.Empty) tb_PocetDni.Text = "1";

            string[] nazvy = new Zbozi().GetAllZboziNames();
            foreach (string s in nazvy) tb_Nazev.AddItem(new AutoCompleteEntry(s, null));

            UpdateStatus();
        }

        private void Okno_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (_zbozi == null) return;

            e.Cancel = MessageBoxResult.Yes !=
                       MessageBox.Show("Opravdu chcete zrušit všechny změny", "Upozornění", MessageBoxButton.YesNo,
                                       MessageBoxImage.Warning);
        }

        #endregion

        #region Události komponentů

        private void tb_CarovyKod_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            switch (e.Text)
            {
                case "-":
                    InputLanguage.CurrentInputLanguage = InputLanguage.FromCulture(new CultureInfo("en-US"));
                    e.Handled = true;
                    break;
                case "(":
                    InputLanguage.CurrentInputLanguage = InputLanguage.FromCulture(new CultureInfo("cs-CZ"));
                    e.Handled = true;
                    break;
            }
        }

        private void tb_CarovyKod_GotFocus(object sender, RoutedEventArgs e)
        {
            if (_zbozi == null) tb_CarovyKod.Text = "";
        }

        private void tb_CarovyKod_LostFocus(object sender, RoutedEventArgs e)
        {
            try
            {
                _zbozi = Zbozi.GetZboziByCode(tb_CarovyKod.Text);
                tb_Nazev.Text = _zbozi.name;
                lb_CenovyProfil.Content = _zbozi.cenovyProfil.name;
            }
            catch (Exception)
            {
                if (tb_CarovyKod.Text.Length <= 0) return;

                MessageBox.Show("Zadali jste neznámý čarový kód!\n\nZboží není rozpoznáno !!", "Upozornění", MessageBoxButton.OK, MessageBoxImage.Warning);
                VynulovatHodnoty();
            }
            finally
            {
                if (_zbozi == null)
                {
                    tb_CarovyKod.Text = "neznámý";

                    _odDne = DateTime.Now;
                    date_OdDne.SelectedDate = _odDne;
                }

                else PrepocitatCenu();

                UpdateStatus();
            }
        }





        private void tb_Nazev_LostFocus(object sender, RoutedEventArgs e)
        {
            try
            {
                _zbozi = Zbozi.GetZboziByName(tb_Nazev.Text);
                tb_CarovyKod.Text = _zbozi.code;
                lb_CenovyProfil.Content = _zbozi.cenovyProfil.name;

                //Uprava Rosko
                _odDne = DateTime.Now;
                //********************
            }
            catch (Exception)
            {
                _zbozi = null;

                lb_CenovyProfil.Content = "neznámý";
                tb_CarovyKod.Text = "neznámý";
                tb_PocetDni.Text = "1";
                sb_Rezerva.Value = 0;
                tb_CelkovaCena.Text = "0";
                _cenaZbozi = 0;

                _odDne = DateTime.Now;
                date_OdDne.SelectedDate = _odDne;
            }
            finally
            {
                PrepocitatCenu();
                UpdateStatus();
            }
        }




        private void tb_PocetDni_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            int result;
            if (!Int32.TryParse(e.Text, out result)) e.Handled = true;
        }

        private void tb_PocetDni_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (tb_PocetDni.Text.Length > 0 && date_OdDne.SelectedDate != null)
            {

                MujKalendar.SelectedDate =
                    MujKalendar.DisplayDate = date_OdDne.SelectedDate.Value.AddDays(int.Parse(tb_PocetDni.Text) +
                                                                                    sb_Rezerva.Value);

            }
            else
            {
                MujKalendar.SelectedDate = MujKalendar.DisplayDate = date_OdDne.SelectedDate.Value.AddDays(1);
            }

            PrepocitatCenu();
        }

        private void tb_PocetDni_LostFocus(object sender, RoutedEventArgs e)
        {
            if (tb_PocetDni.Text == string.Empty) tb_PocetDni.Text = "1";
        }




        private void date_OdDne_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            int pocet = PocetDnu(_odDne, (DateTime)date_OdDne.SelectedDate);
            if (pocet < 0)
            {
                MessageBox.Show("Neplatné datum!\nZvolte znovu!", "Upozornění", MessageBoxButton.OK,
                                MessageBoxImage.Warning);
                date_OdDne.SelectedDate = _odDne;
            }

            else
            {
                // resetuje moznosti
                sb_Rezerva.Value = 0;
                tb_PocetDni.Text = "1";
                MujKalendar.SelectedDate = MujKalendar.DisplayDate = date_OdDne.SelectedDate.Value.AddDays(1);
            }
        }


        private void sb_Rezerva_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (MujKalendar.SelectedDate != null && sb_Rezerva.Value > 0)
            {
                string s = tb_PocetDni.Text;
                DateTime dt = MujKalendar.SelectedDate.Value.AddDays(sb_Rezerva.Value);
                MujKalendar.SelectedDate = MujKalendar.DisplayDate = dt;
                tb_PocetDni.Text = s;
            }

            if (sb_Rezerva.Value == 0 && date_OdDne.SelectedDate != null)
                MujKalendar.SelectedDate = MujKalendar.DisplayDate =
                    date_OdDne.SelectedDate.Value.AddDays(int.Parse(tb_PocetDni.Text));
        }

        private void Calendar_SelectedDatesChanged_1(object sender, SelectionChangedEventArgs e)
        {
            if (date_OdDne.SelectedDate == null) return;

            int pocet = PocetDnu((DateTime)date_OdDne.SelectedDate, (DateTime)MujKalendar.SelectedDate);
            if (pocet <= 0)
            {
                MessageBox.Show("Neplatné datum!\nZvolte znovu!", "Upozornění", MessageBoxButton.OK, MessageBoxImage.Warning);
                sb_Rezerva.Value = 0;
                tb_PocetDni.Text = "1";
                MujKalendar.SelectedDate = MujKalendar.DisplayDate = date_OdDne.SelectedDate.Value.AddDays(1);
            }

            else tb_PocetDni.Text = (pocet - sb_Rezerva.Value).ToString();

            lb_DatumVraceni.Content = MujKalendar.DisplayDate.ToString("dddd, dd MMMM, " + MujKalendar.DisplayDate.Year);
        }




        private void tb_CelkovaCena_TextChanged(object sender, TextChangedEventArgs e)
        {
            String pom = tb_CelkovaCena.Text;

            int cislo = Int32.Parse(pom);
            if ((pom.Length > 0) && (cislo > 0))
                _cenaZbozi = cislo;
        }

        private void tb_CelkovaCena_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            int result;
            if (!Int32.TryParse(e.Text, out result)) e.Handled = true;
        }

        #endregion

        #region Potvrdit, Storno

        // delegát
        public delegate void PridatZboziHandler(object sender, PridatZboziEventArgs e);

        public event PridatZboziHandler PridatZbozi;

        private void bt_Pridat_Click(object sender, RoutedEventArgs e)
        {
            if (tb_Nazev.Text == "")
                MessageBox.Show("Zvolte název zboží !", "Upozornění", MessageBoxButton.OK, MessageBoxImage.Warning);

            else if (_cenaZbozi == 0)
                MessageBox.Show("Zvolte cenu zboží !", "Upozornění", MessageBoxButton.OK, MessageBoxImage.Warning);

            else if (_zbozi == null)
            {
                PridatZboziEventArgs args = new PridatZboziEventArgs(string.Empty, string.Empty, tb_Nazev.Text,
                                                                        _cenaZbozi.ToString(),
                                                                        (DateTime)date_OdDne.SelectedDate,
                                                                        tb_PocetDni.Text,
                                                                        (int)sb_Rezerva.Value,
                                                                        (DateTime)MujKalendar.SelectedDate);
                PridatZbozi(this, args);

                _zbozi = null;
                this.Close();
            }

            else
            {
                PridatZboziEventArgs args = new PridatZboziEventArgs(tb_CarovyKod.Text, _zbozi.cenovyProfil.prefix, tb_Nazev.Text,
                                                                        _cenaZbozi.ToString(),
                                                                        (DateTime)date_OdDne.SelectedDate,
                                                                        tb_PocetDni.Text,
                                                                        (int)sb_Rezerva.Value,
                                                                        (DateTime)MujKalendar.SelectedDate);
                PridatZbozi(this, args);

                _zbozi = null;
                this.Close();
            }
        }

        private void bt_Storno_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        #endregion

    }
}
